package com.hq.signatureapplication;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 签字版
 * Created by longqin on 2018/1/31.
 */

public class WritePadDialog extends Dialog {

    private String TAG = "WritePadDialog";
    private Context mContext;
    private WriteDialogListener mWriteDialogListener;
    private WritePadView mPaintView;
    private FrameLayout mFrameLayout;
    private Button mBtnOK, mBtnClear, mBtnCancel,btn_enlarge;
    private LinearLayout ll_title;
    private LinearLayout ll_tool;
    private Activity _activity;
    /**
     * 是否全屏
     */
    private boolean isFullScreen;

    /**
     * 完成签名时是否关闭
     */
    private boolean isAccomplishClose;

    public WritePadDialog(Context context, Activity activity, WriteDialogListener writeDialogListener) {
        super(context);
        this.mContext = context;
        this._activity = activity;
        this.mWriteDialogListener = writeDialogListener;
        this.isFullScreen = false;
        this.isAccomplishClose = true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //无标题
        setContentView(R.layout.write_pad);
        //设置点击空白处不关闭
        this.setCanceledOnTouchOutside(false);
        this.onSizeChanged();
        //监听物理按钮
        this.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if(keyCode==KeyEvent.KEYCODE_BACK){
                    //禁止返回按钮关闭
                    return true;
                }
                return false;
            }
        });
        //确定按钮
        mBtnOK = (Button) findViewById(R.id.write_pad_ok);
        mBtnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPaintView.getPath().isEmpty()) {
                    Toast.makeText(mContext, "请挥笔写下您的大名", Toast.LENGTH_SHORT).show();
                    return;
                }
                mWriteDialogListener.onPaintDone(mPaintView.getResizeBitmap((float) 1.8));
                if(isAccomplishClose){
                    closeAfter();
                    dismiss();
                }else{
                    mPaintView.clear();
                }
            }
        });
        //清除按钮
        mBtnClear = (Button) findViewById(R.id.write_pad_clear);
        mBtnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPaintView.clear();
            }
        });
        //取消按钮
        mBtnCancel = (Button) findViewById(R.id.write_pad_cancel);
        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
                closeAfter();
            }
        });
        //点击横屏
        btn_enlarge = (Button)this.findViewById(R.id.btn_enlarge);
        btn_enlarge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
                    _activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
                }else{
                    _activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
                }
            }
        });
    }
    /**
     * 关闭后
     */
    public void closeAfter (){
        //如果不等于竖屏
        if(mContext.getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT){
            _activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        }
        mPaintView.clear();
    }

    /**
     * 设置dialog大小改变
     */
    public void onSizeChanged(){
        if(mPaintView != null){
            mPaintView.clear();
            mPaintView = null;
        }
        //获取屏幕状态
        int orientationType = this.mContext.getResources().getConfiguration().orientation;
        mFrameLayout = (FrameLayout)findViewById(R.id.tablet_view);
        ll_title = (LinearLayout)findViewById(R.id.ll_title);
        ll_tool = (LinearLayout)findViewById(R.id.ll_tool);
        //获取标题高度
        ViewGroup.LayoutParams title_layoutParams = ll_title.getLayoutParams();
        int titleHeight = title_layoutParams.height;
        //获取工具高度
        ViewGroup.LayoutParams tool_layoutParams  = ll_tool.getLayoutParams();
        int toolHeight = tool_layoutParams.height;

        int otherHeight = toolHeight + titleHeight;

        // 获取屏幕尺寸
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        WindowManager m = getWindow().getWindowManager();
        m.getDefaultDisplay().getMetrics(mDisplayMetrics);
        //获取屏幕的宽高
        int screenWidth = mDisplayMetrics.widthPixels;
        int screenHeight = mDisplayMetrics.heightPixels;
        Window dialogWindow = this.getWindow();
        //设置弹出框大小
        int pWidth = 0,pHeight = 0,
                WritePadViewHeight = 0, // 画布高度
                strokeWidth = 5; //画笔大小
        if(Configuration.ORIENTATION_PORTRAIT == orientationType){
            //竖屏
            pWidth = screenWidth;
            pHeight = (int) (pWidth / 1.8) + otherHeight;
            dialogWindow.setGravity(Gravity.BOTTOM);
            strokeWidth = 5;
        }else {
            pHeight = screenHeight;
            pWidth = (int) ((pHeight) * 1.8);
            dialogWindow.setGravity(Gravity.CENTER);
            strokeWidth = 8;
        }
        WritePadViewHeight = pHeight - otherHeight;
        //设置弹出框的大小
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = pHeight;
        p.width = pWidth;
        dialogWindow.setAttributes(p);
        mPaintView = new WritePadView(mContext, pWidth, WritePadViewHeight,strokeWidth);
        mFrameLayout.addView(mPaintView);
        mPaintView.requestFocus();
    }

    /**
     * 弹出窗体
     */
    @Override
    public void show(){
        super.show();
        if(this.isFullScreen){
            _activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
        }
    }

    /**
     * 设置全屏弹出(需要在调用show方法前设置)
     * @param fullScreen true 横屏弹出，false 竖屏弹出
     */
    public void setFullScreen(boolean fullScreen) {
        this.isFullScreen = fullScreen;
    }

    /**
     * 设置点击确定按钮是否关闭dialog窗体
     * @param accomplishClose 默认值为true（关闭），false 为不关闭
     */
    public void setAccomplishClose(boolean accomplishClose) {
        isAccomplishClose = accomplishClose;
    }

    /**
     * 保存方法
     * @param bm 图片
     * @param path 路径
     * @param name 文件名称
     * @return
     */
    public boolean saveBitmap(Bitmap bm, String path,String name) {
        boolean isSuccess = true;
        Log.e(TAG, "保存图片");
        File f = new File(path, name);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i(TAG, "已经保存");
            isSuccess = true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            isSuccess = false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * 监听手写板对话框
     * @author longqin
     *
     */
    public interface WriteDialogListener {
        void onPaintDone(Object object);

    }

}
